import { parseURL } from './token'

export function isWx() {
  const ua = window.navigator.userAgent
  const reg = /wanxiao/gi
  if (reg.test(ua)) {
    return true
  }
  return false
}

export function isSuperApp() {
  // 树维超级app
  const ua = window.navigator.userAgent
  const reg = /superapp/gi
  if (reg.test(ua)) {
    return true
  }
  return false
}

export function isIos() {
  const u = navigator.userAgent
  return !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)
}

export function isAndroid() {
  const u = navigator.userAgent
  return u.indexOf('Android') > -1 || u.indexOf('Linux') > -1
}

// 是否是移动端
export function isMobile() {
  return /iPhone|iPad|iPod|Android|OpenHarmony/i.test(navigator.userAgent)
}

export function isWeixinMini() {
  const ua = window.navigator.userAgent.toLowerCase()
  return ua.indexOf('miniprogram') > -1 && ua.indexOf('micromessenger') > -1
}

export function isWeixinMiniProgram() {
  return typeof wx !== 'undefined' && wx.miniProgram
}

// 跳转http
export function jumpHttp(url) {
  console.log(url)
  if (!isMobile()) {
    console.log('pc环境')
    window.open(url)
  } else if (isWx()) {
    console.log('完美校园环境')
    // 兼容智慧用水
    const parsedUrl = parseURL(url)
    if (
      parsedUrl.host + parsedUrl.path ===
      'vwater.59wanmei.com/usewater/api/use-water/entrance'
    ) {
      url =
        'https://vwater.59wanmei.com/usewater/api/use-water/entrance?source=wx'
    }
    wanxiao.openNewWebview(url)
  } else if (isWeixinMini()) {
    console.log('微信小程序环境')
    wx.miniProgram.navigateTo({
      url: `/pages/webview/webview?url=${encodeURIComponent(url)}`
    })
  } else {
    console.log('其他环境')
    window.location.href = url
  }
}

export function getExt(url) {
  const arr = url.split('.')
  return arr[arr.length - 1]
}

// 获取queto所有img的src
const exts = ['png', 'jpg', 'bmp', 'webp', 'gif']
const isImg = (src) => {
  return exts.indexOf(getExt(src).toLowerCase()) !== -1
}
export function getAllSrc(htmlString) {
  const parser = new DOMParser()
  const doc = parser.parseFromString(htmlString, 'text/html')
  const imgElements = doc.querySelectorAll('img')
  const imgList = Array.from(imgElements).map((img) => {
    return img.src
  })
  return imgList.filter((src) => {
    return isImg(src)
  })
}
